import { getAppVersion } from '@/api/common/version'

/**
 * Compare version strings
 * @param newVersion 
 * @param oldVersion 
 * @returns true if newVersion is greater than oldVersion
 */
function compareVersion(newVersion: string, oldVersion: string): boolean {
  const newParts = newVersion.split('.')
  const oldParts = oldVersion.split('.')
  
  // Compare each segment of the version
  for (let i = 0; i < Math.max(newParts.length, oldParts.length); i++) {
    const newVal = parseInt(newParts[i] || '0')
    const oldVal = parseInt(oldParts[i] || '0')
    
    if (newVal > oldVal) return true
    if (newVal < oldVal) return false
  }
  
  return false
}

/**
 * Check for app updates
 */
export async function checkUpdate() {
  try {
    // Get current app version
    const currentVersion = plus.runtime.version
    
    // Get latest version info from server
    const res = await getAppVersion()
    const versionInfo = res.result
    
    // If there's no update needed
    if (!compareVersion(versionInfo.version, currentVersion)) {
      return
    }
    
    // Show update modal
    uni.showModal({
      title: 'New Update Available',
      content: `Version ${versionInfo.version} is available. ${versionInfo.changelog}`,
      confirmText: 'Update Now',
      cancelText: versionInfo.forceUpdate ? '' : 'Later',
      success: (res) => {
        if (res.confirm) {
          // Handle the update
          handleUpdate(versionInfo)
        } else if (versionInfo.forceUpdate) {
          // If update is mandatory and user tries to cancel, show the dialog again
          checkUpdate()
        }
      }
    })
  } catch (error) {
    console.error('Failed to check for updates:', error)
  }
}

/**
 * Handle the actual update process
 */
function handleUpdate(versionInfo: any) {
  // WGT package takes priority over full package
  const isWgtUpdate = !!versionInfo.wgtUrl
  const downloadUrl = isWgtUpdate ? versionInfo.wgtUrl : versionInfo.pkgUrl
  
  // Validate URL exists
  if (!downloadUrl) {
    uni.showModal({
      title: 'Update Failed',
      content: 'Update package URL is missing.',
      showCancel: false
    })
    return
  }
  
  // Download the update package
  const downloadTask = uni.downloadFile({
    url: downloadUrl,
    success: (res) => {
      if (res.statusCode === 200) {
        // For wgt package (hot update)
        if (isWgtUpdate) {
          installWgtPackage(res.tempFilePath)
        } 
        // For full package update (apk/ipa)
        else {
          installFullPackage(res.tempFilePath, versionInfo.pkgUrl)
        }
      } else {
        showUpdateFailedModal()
      }
    },
    fail: () => {
      showUpdateFailedModal()
    }
  })
  
  // Show download progress
  downloadTask.onProgressUpdate((res) => {
    uni.showLoading({
      title: `Downloading: ${res.progress}%`,
      mask: true
    })
    
    if (res.progress === 100) {
      uni.hideLoading()
    }
  })
}

/**
 * Install WGT hot update package
 */
function installWgtPackage(filePath: string) {
  plus.runtime.install(
    filePath, 
    { force: false },
    () => {
      uni.showModal({
        title: 'Update Complete',
        content: 'The application needs to restart to apply the update.',
        showCancel: false,
        success: () => {
          plus.runtime.restart()
        }
      })
    },
    () => {
      showUpdateFailedModal()
    }
  )
}

/**
 * Handle full package installation
 */
function installFullPackage(filePath: string, storeUrl: string) {
  // Android - install APK
  if (uni.getSystemInfoSync().platform === 'android') {
    plus.runtime.openFile(filePath)
  } 
  // iOS - open App Store
  else {
    plus.runtime.openURL(storeUrl)
  }
}

/**
 * Show update failed modal
 */
function showUpdateFailedModal() {
  uni.showModal({
    title: 'Update Failed',
    content: 'Please try again later or download the latest version from our website.',
    showCancel: false
  })
} 